package com.vitabuybuy.tv.ui.shopcenter

import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import com.google.gson.reflect.TypeToken
import com.library.common.base.BaseActivity
import com.library.common.ext.mmkv
import com.vitabuybuy.tv.BR
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivitySearchGoodsBinding
import com.vitabuybuy.tv.dialog.OptionsDialog
import com.library.common.toast.XToast
import com.library.common.util.JsonUtil
import com.tencent.mmkv.MMKV
import com.vitabuybuy.tv.dto.FirstCategoryDto
import com.vitabuybuy.tv.ui.shopcenter.viewmodel.SearchGoodsOrStoreViewModel
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.utils.KeyBoardUtils

import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import kotlinx.android.synthetic.main.activity_search_goods.*
import java.util.ArrayList

/**
 * 作者：SimGa
 * 日期：2020/12/5
 * 时间：14:16
 * 包名：com.vitabuybuy.tv.ui.shopcenter
 */
internal class SearchGoodsOrStoreActivity :
    BaseActivity<SearchGoodsOrStoreViewModel, ActivitySearchGoodsBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.activity_search_goods

    private val bottomDialog by lazy { OptionsDialog(mContext) }

    val tiplist = ArrayList<String>()

    var storeId: Int? = null
    override fun onGetBundle(bundle: Bundle?) {
        storeId = bundle?.getInt("storeId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.setVariable(BR.isStore, storeId != null && storeId != 0)
        if (!mBinding.isStore!!) {
            tvSearchTitle.text = getString(R.string.hot_search)
        } else {
            tvSearchTitle.text = getString(R.string.history_search)
        }
        bottomDialog.setBtnStr(getString(R.string.shop), getString(R.string.commodity))
        tagLayout!!.adapter = object : TagAdapter<String>(tiplist) {
            override fun getView(parent: FlowLayout, position: Int, str: String): View {
                val tvTip = LayoutInflater.from(mContext).inflate(
                    R.layout.item_tag,
                    tagLayout, false
                ) as TextView
                tvTip.text = str
                val ll = tvTip.layoutParams as ViewGroup.MarginLayoutParams
                ll.rightMargin = 50
                ll.bottomMargin = 40
                tvTip.layoutParams = ll
                return tvTip
            }
        }
    }

    override fun onResume() {
        super.onResume()
        Handler().postDelayed({
            KeyBoardUtils.showSoftInputFromWindow(mContext, etSearch)
        }, 300)
    }

    override fun observeData() {
        if (mBinding.isStore!!) {
            val histories = JsonUtil.fromJson(mmkv.decodeString(MMKVContancts.SEARCH_HOTE_HISTORY, ""),
                object : TypeToken<ArrayList<String>>() {}.type) as? ArrayList<String>
            histories?.run {
                tiplist.addAll(this)
                tagLayout.adapter.notifyDataChanged()
            }
        } else {
            viewModel.gethotKey()
            viewModel.hotKeylist.observe(this, Observer {
                for (str in it) {
                    tiplist.add(str.name)
                }
                tagLayout.adapter.notifyDataChanged()
            })
        }
    }

    override fun eventHandling() {
        tagLayout.setOnTagClickListener { _, position, _ ->
            if (mBinding.isStore!!) {
                SearchStoreResultActivity.openActivity(
                    mContext,
                    etSearch.text.toString()
                )
            } else {
                CateSearchGoodsResultActivity.openActivity(
                    mContext,
                    null,
                    storeId,
                    null,
                    tiplist[position]
                )
            }
//            finish()
            true
        }
        etSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search()
                true
            }
            false
        }
        iv_back.setOnClickListener {
            finish()
        }
        tvSearchClass.setOnClickListener {
            bottomDialog.show()
        }
        bottomDialog.onOneClick = {
            tvSearchClass.text = getString(R.string.shop)
        }
        bottomDialog.onTwoClick = {
            tvSearchClass.text = getString(R.string.commodity)
        }
        tvClear.setOnClickListener {
            mmkv.remove(MMKVContancts.SEARCH_HOTE_HISTORY)
            tiplist.clear()
            tagLayout.adapter.notifyDataChanged()
        }
    }

    fun search() {
        when {
            etSearch.text.isNullOrEmpty() -> XToast.normal(getString(R.string.enter_search_content))
            else -> {
                if (tvSearchClass.text == getString(R.string.commodity)) {
                    if (mBinding.isStore!!) {
                        if (!tiplist.contains(etSearch.text.toString()))
                            tiplist.add(etSearch.text.toString())
                        tagLayout.adapter.notifyDataChanged()
                        mmkv.encode(MMKVContancts.SEARCH_HOTE_HISTORY, JsonUtil.toJson(tiplist))
                    }
                    CateSearchGoodsResultActivity.openActivity(
                        mContext,
                        null,
                        storeId, null,
                        etSearch.text.toString()
                    )
                } else {
                    SearchStoreResultActivity.openActivity(
                        mContext,
                        etSearch.text.toString()
                    )
                }
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, SearchGoodsOrStoreActivity::class.java)
        }

        fun openActivity(mContext: BaseActivity<*, *>, storeId: Int?) {
            mContext.startActivity(
                bundleOf(Pair("storeId", storeId)),
                SearchGoodsOrStoreActivity::class.java
            )
        }
    }
}